<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>高级图片水印工具 - 在线工具集合</title>
    <script src="../utils/toast.js"></script>
    <link rel="stylesheet" href="../utils/styles.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);
            min-height: 100vh;
            color: #fff;
            position: relative;
            overflow-x: hidden;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 40px 20px;
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            background: linear-gradient(45deg, #00ff88, #00b4d8);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .header p {
            color: rgba(255, 255, 255, 0.8);
            font-size: 1.1em;
        }

        .watermark-section {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 24px;
            padding: 30px;
            margin-bottom: 30px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
        }

        .upload-area {
            border: 2px dashed rgba(255, 255, 255, 0.2);
            border-radius: 20px;
            padding: 40px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 30px;
        }

        .upload-area:hover {
            border-color: #00ff88;
            background: rgba(255, 255, 255, 0.05);
        }

        .watermark-options {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .option-group {
            background: rgba(255, 255, 255, 0.05);
            padding: 20px;
            border-radius: 12px;
        }

        .option-group label {
            display: block;
            margin-bottom: 10px;
            color: rgba(255, 255, 255, 0.9);
        }

        .option-group select,
        .option-group input[type="text"],
        .option-group input[type="number"],
        .option-group input[type="color"] {
            width: 100%;
            padding: 8px;
            background: rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 6px;
            color: #fff;
            transition: all 0.3s;
        }

        .option-group select:hover,
        .option-group input:hover {
            border-color: #00ff88;
        }

        .option-group select option {
            background: rgba(0, 0, 0, 0.7);
            color: #fff;
        }

        .position-selector {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 5px;
            margin-top: 10px;
        }

        .position-btn {
            aspect-ratio: 1;
            background: rgba(255,255,255,0.1);
            border: 1px solid rgba(255,255,255,0.2);
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .position-btn.active {
            background: #00ff88;
            border-color: #00ff88;
            box-shadow: 0 0 8px rgba(0, 255, 136, 0.5);
        }

        .preview-area {
            margin-top: 30px;
            text-align: center;
        }

        .preview-area canvas {
            max-width: 100%;
            border-radius: 12px;
            background: rgba(255, 255, 255, 0.05);
        }

        .action-buttons {
            display: flex;
            gap: 20px;
            justify-content: center;
            margin-top: 30px;
        }

        .action-btn {
            padding: 15px 30px;
            border: none;
            border-radius: 12px;
            background: linear-gradient(45deg, #00ff88, #00b4d8);
            color: #1a1a1a;
            font-size: 1.1em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 255, 136, 0.2);
        }

        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0, 255, 136, 0.3);
        }

        .back-link {
            display: inline-block;
            margin-bottom: 20px;
            color: #00ff88;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .back-link:hover {
            transform: translateX(-5px);
        }

        @media (max-width: 768px) {
            .watermark-options {
                grid-template-columns: 1fr;
            }

            .action-buttons {
                flex-direction: column;
            }

            .action-btn {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="../index.html" class="back-link">← 返回首页</a>
        
        <div class="header">
            <h1>高级图片水印工具</h1>
            <p>支持多种模式的专业水印解决方案</p>
        </div>

        <div class="watermark-section">
            <div class="upload-area" id="uploadArea">
                <div class="upload-text">点击或拖拽图片到这里</div>
                <input type="file" id="imageInput" accept="image/*" style="display: none;">
            </div>

            <div class="watermark-options">
                <div class="option-group">
                    <label>水印类型</label>
                    <select id="watermarkType">
                        <option value="single">单次显示</option>
                        <option value="repeat">重复平铺</option>
                    </select>
                </div>
                
                <div class="option-group">
                    <label>水印文本</label>
                    <input type="text" id="watermarkText" placeholder="输入水印文字..." value="Sample Watermark">
                </div>

                <div class="option-group">
                    <label>字体选择</label>
                    <select id="fontFamily">
                        <option value="Arial">Arial</option>
                        <option value="SimSun">宋体</option>
                        <option value="Microsoft YaHei">微软雅黑</option>
                        <option value="KaiTi">楷体</option>
                    </select>
                </div>

                <div class="option-group">
                    <label>字体大小</label>
                    <input type="number" id="fontSize" value="24" min="8" max="72">
                </div>

                <div class="option-group">
                    <label>水印颜色</label>
                    <input type="color" id="watermarkColor" value="#ffffff">
                </div>

                <div class="option-group">
                    <label>透明度</label>
                    <input type="number" id="opacity" value="50" min="0" max="100">
                </div>

                <div class="option-group">
                    <label>排列方式</label>
                    <select id="textDirection">
                        <option value="0">水平</option>
                        <option value="45">45度</option>
                        <option value="-45">-45度</option>
                        <option value="90">垂直</option>
                    </select>
                </div>

                <div class="option-group">
                    <label>水印位置</label>
                    <div class="position-selector" id="positionSelector">
                        <button data-pos="left-top" class="position-btn"></button>
                        <button data-pos="center-top" class="position-btn"></button>
                        <button data-pos="right-top" class="position-btn"></button>
                        <button data-pos="left-center" class="position-btn"></button>
                        <button data-pos="center-center" class="position-btn"></button>
                        <button data-pos="right-center" class="position-btn"></button>
                        <button data-pos="left-bottom" class="position-btn"></button>
                        <button data-pos="center-bottom" class="position-btn"></button>
                        <button data-pos="right-bottom" class="position-btn"></button>
                    </div>
                </div>
            </div>

            <div class="preview-area">
                <canvas id="previewCanvas"></canvas>
            </div>

            <div class="action-buttons">
                <button class="action-btn" id="addWatermarkBtn">应用水印</button>
                <button class="action-btn" id="removeWatermarkBtn">清除水印</button>
                <button class="action-btn" id="downloadBtn">下载图片</button>
            </div>
        </div>
    </div>

    <script>
        const uploadArea = document.getElementById('uploadArea');
        const imageInput = document.getElementById('imageInput');
        const watermarkText = document.getElementById('watermarkText');
        const fontSize = document.getElementById('fontSize');
        const watermarkColor = document.getElementById('watermarkColor');
        const opacity = document.getElementById('opacity');
        const watermarkType = document.getElementById('watermarkType');
        const fontFamily = document.getElementById('fontFamily');
        const textDirection = document.getElementById('textDirection');
        const positionBtns = document.querySelectorAll('.position-btn');
        const canvas = document.getElementById('previewCanvas');
        const ctx = canvas.getContext('2d');
        
        let originalImage = null;
        let currentPosition = 'center-center';

        // 初始化位置选择
        positionBtns.forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                positionBtns.forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                currentPosition = btn.dataset.pos;
                updatePreview();
            });
        });

        // 文件处理
        uploadArea.addEventListener('click', () => imageInput.click());
        uploadArea.addEventListener('dragover', (e) => e.preventDefault());
        uploadArea.addEventListener('drop', handleDrop);
        imageInput.addEventListener('change', handleFileSelect);

        function handleDrop(e) {
            e.preventDefault();
            const file = e.dataTransfer.files[0];
            file && handleImage(file);
        }

        function handleFileSelect(e) {
            const file = e.target.files[0];
            file && handleImage(file);
        }

        function handleImage(file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                const img = new Image();
                img.onload = () => {
                    originalImage = img;
                    canvas.width = img.width;
                    canvas.height = img.height;
                    updatePreview();
                };
                img.src = e.target.result;
            };
            reader.readAsDataURL(file);
        }

        // 计算水印位置
        function getPositionCoordinates(textWidth, textHeight, padding) {
            const [vertical, horizontal] = currentPosition.split('-');

            // 计算安全区域
            const safeArea = {
                left: padding + textWidth/2,
                right: canvas.width - padding - textWidth/2,
                top: padding + textHeight/2,
                bottom: canvas.height - padding - textHeight/2
            };

            let x, y;
            /// 水平方向
            switch(vertical) {
                case 'left': x = safeArea.left; break;
                case 'right': x = safeArea.right; break;
                default: x = canvas.width/2;
            }

            // 垂直方向
            switch(horizontal) {
                case 'top': y = safeArea.top; break;
                case 'bottom': y = safeArea.bottom; break;
                default: y = canvas.height/2;
            }

            // 旋转补偿（示例处理45度）
            if(Math.abs(parseInt(textDirection.value)) === 45) {
                const diagonal = Math.sqrt(textWidth**2 + textHeight**2)/2;
                x = Math.max(diagonal, Math.min(canvas.width - diagonal, x));
                y = Math.max(diagonal, Math.min(canvas.height - diagonal, y));
            }


            // 调试输出（正式版可移除）
            console.log(`位置: ${currentPosition}, 计算坐标: X=${x}, Y=${y}`);
            return { x, y };
        }

        // 绘制水印
        function drawWatermark() {
            ctx.save();
            const text = watermarkText.value;
            const angle = parseInt(textDirection.value);
            const fontSizeValue = fontSize.value;
            const font = `${fontSizeValue}px ${fontFamily.value}`;
            const opacityValue = opacity.value / 100;
            const color = `${watermarkColor.value}${Math.round(opacityValue * 255).toString(16).padStart(2, '0')}`;
            
            ctx.font = font;
            ctx.fillStyle = color;
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';


            // 获取文本尺寸
            ctx.font = `${fontSizeValue}px ${fontFamily.value}`;
            const textMetrics = ctx.measureText(text);
            const textWidth = textMetrics.width;
            const textHeight = fontSizeValue * 1.2; // 估算高度

            // 智能边距计算
            const minPadding = 10; // 最小边距
            const dynamicPadding = Math.max(
                minPadding,
                textWidth * 0.3,
                textHeight * 0.5
            );

            const { x, y } = getPositionCoordinates(textWidth, textHeight, dynamicPadding);

            ctx.translate(x, y);
            ctx.rotate(angle * Math.PI / 180);

            if (watermarkType.value === 'single') {
                ctx.fillText(text, 0, 0);
            } else {
                const textWidth = ctx.measureText(text).width;
                const spacing = textWidth * 2;
                
                for(let dx = -canvas.width; dx < canvas.width*2; dx += spacing){
                    for(let dy = -canvas.height; dy < canvas.height*2; dy += spacing){
                        ctx.fillText(text, dx, dy);
                    }
                }
            }
            ctx.restore();
        }

        // 更新预览
        function updatePreview() {
            if (!originalImage) return;
            
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(originalImage, 0, 0);
            drawWatermark();
        }

        // 事件监听
        [watermarkText, fontSize, watermarkColor, opacity, watermarkType, fontFamily, textDirection]
            .forEach(input => input.addEventListener('input', updatePreview));

        document.getElementById('addWatermarkBtn').addEventListener('click', () => {
            originalImage && toast.success('水印应用成功');
        });

        document.getElementById('removeWatermarkBtn').addEventListener('click', () => {
            if (originalImage) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(originalImage, 0, 0);
                toast.success('已清除水印');
            }
        });

        document.getElementById('downloadBtn').addEventListener('click', () => {
            if (!originalImage) return;
            const link = document.createElement('a');
            link.download = 'watermarked_image.png';
            link.href = canvas.toDataURL();
            link.click();
            toast.success('开始下载图片');
        });

        // 初始化默认位置
        document.querySelector('[data-pos="center-center"]').click();
    </script>
</body>
</html>